<template>
  <md-popup v-model="show" position="bottom">
    <md-popup-title-bar only-close :title="$t('union.vote') + form.name" :describe="$t('union.vote_describe')" title-align="left" @cancel="show = false" />
    <div style="background: #fff; padding: 20px">
      <md-input-item v-model="form.num" type="money" is-highlight>
        <template #right>
          {{ $t('union.vote_my') }} {{ userData.vote_num.unused }} {{ $t('union.unit') }}
        </template>
      </md-input-item>
      <div style="padding-top: 20px">
        <md-button type="primary" :loading="loading" @click="action" round>{{ $t('union.vote') }}</md-button>
      </div>
    </div>
  </md-popup>
  <Confirm ref="confirm" />
</template>

<script setup>
import { ref } from 'vue'
import { toast, dialog } from '@/style'
import { t } from '@/lang'
import { packager, random } from '@/web3'
import { userData, userInfo } from '@/model/user'
import { batch } from '@/api/vote'
import Nav from '@/components/nav.vue'
import Confirm from '@/components/confirm.vue'

const emit = defineEmits(['confirm'])

const confirm = ref(null)
const show = ref(false)
const loading = ref(false)
const form = ref({
  vote_to: 0,
  name: '',
  num: 1
})

const open = (data) => {
  show.value = true
  form.value.vote_to = data.id
  form.value.name = data.name
  form.value.num = 1
}

const action = async() => {
  // 合并数据加入随机符
  const data = Object.assign({random: random()}, form.value)
  // 打包数据
  const pack = await packager(data)
  loading.value = true
  batch(pack).then(res => {
    toast(t('ok'))
    show.value = false
    userInfo()
    emit('confirm')
  }).catch(err => {
    toast(err.message)
  }).finally(() => {
    loading.value = false
  })
}

defineExpose({ open })

</script>